#!/bin/bash

# AI Meeting Minutes 停止服务脚本

set -e

echo "🛑 停止 AI Meeting Minutes 系统..."

# 读取PID文件
BACKEND_PID=""
FRONTEND_PID=""

if [ -f ".backend.pid" ]; then
    BACKEND_PID=$(cat .backend.pid)
    echo "🔧 停止后端服务 (PID: $BACKEND_PID)..."
    if kill -0 $BACKEND_PID 2>/dev/null; then
        echo "✅ 后端服务已停止"
    else
        echo "⚠️  后端服务已不在运行"
    fi
    rm -f .backend.pid
else
    echo "⚠️  找不到后端服务PID文件"
fi

if [ -f ".frontend.pid" ]; then
    FRONTEND_PID=$(cat .frontend.pid)
    echo "🔧 停止前端服务 (PID: $FRONTEND_PID)..."
    if kill -0 $FRONTEND_PID 2>/dev/null; then
        echo "✅ 前端服务已停止"
    else
        echo "⚠️  前端服务已不在运行"
    fi
    rm -f .frontend.pid
else
    echo "⚠️  找不到前端服务PID文件"
fi

# 尝试停止可能残留的进程
echo "🔍 检查并停止残留进程..."

# 停止可能的Python进程
PIDS=$(ps aux | grep "simple_main.py" | grep -v grep | awk '{print $2}')
if [ ! -z "$PIDS" ]; then
    echo "🔧 停止残留的Python进程..."
    echo "$PIDS" | xargs kill -9 2>/dev/null || true
fi

# 停止可能的Node.js进程
PIDS=$(ps aux | grep "npm run dev" | grep -v grep | awk '{print $2}')
if [ ! -z "$PIDS" ]; then
    echo "🔧 停止残留的Node.js进程..."
    echo "$PIDS" | xargs kill -9 2>/dev/null || true
fi

PIDS=$(ps aux | grep "vite" | grep -v grep | awk '{print $2}')
if [ ! -z "$PIDS" ]; then
    echo "🔧 停止残留的Vite进程..."
    echo "$PIDS" | xargs kill -9 2>/dev/null || true
fi

echo "✅ 所有服务已停止"
echo ""
echo "📊 查看日志文件："
echo "   后端日志: logs/backend.log"
echo "   前端日志: logs/frontend.log"
echo ""
echo "🔄 重新启动:"
echo "   ./start_local.sh"